﻿using System;
using System.Linq;
using System.Reflection;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using TfsCommitMonitor.Tests.Mocking;
using TfsCommitMonitor.Tfs;

namespace TfsCommitMonitor.Tests
{
	[TestClass]
	public class ProjectTest
	{
		[TestInitialize()]
		public void TestInitialize()
		{
			var isolatedProjectCollectionFileName = typeof(Configuration).GetField("_isolatedProjectCollectionFileName", BindingFlags.NonPublic | BindingFlags.Static);
			isolatedProjectCollectionFileName.SetValue(null, String.Format("unitTest_{0}", Configuration.IsolatedProjectCollectionFileName));
			Configuration.Instance.MaxChangesToPersist = 10;
			Configuration.Instance.MaxNumberOfChangesetsOnInitialLoad = 15;
		}

		[TestMethod]
		public void MarkAsReadTest()
		{
			Changeset[] results =
				new MockTfsPoller().PollForChanges(null)
				.ToArray();

			Project target = new Project();
			StoreChangesets(target, results);
			target.Changesets.Last().Read = true;

			var readChangesets =
				target.Changesets
				.Where(changeset => changeset.Read);

			int expected = 1;
			int actual =
				readChangesets
				.Count();

			Assert.AreEqual(expected, actual);

			target.MarkAsRead();

			expected = target.Changesets.Count();
			actual = readChangesets.Count();

			Assert.AreEqual(expected, actual);
		}

		private static void StoreChangesets(Project project, Changeset[] changesets)
		{
			var storeChangesetsMethod = typeof(Project).GetMethod("StoreChangesets", BindingFlags.NonPublic | BindingFlags.Instance);
			storeChangesetsMethod.Invoke(project, new Object[] { changesets, });
		}

		[TestMethod]
		public void StoreChangesetsTest()
		{
			Changeset[] results =
				new MockTfsPoller().PollForChanges(null)
				.Skip(5)
				.ToArray();

			Project target = new Project();
			StoreChangesets(target, results);

			results =
				new MockTfsPoller().PollForChanges(results.Max(r => r.ChangesetId));

			StoreChangesets(target, results);

			int expected = Configuration.Instance.MaxChangesToPersist;
			int actual = target.Changesets.Count();
			Assert.AreEqual(expected, actual);

			expected = results.Max(r => r.ChangesetId);
			actual = target.Changesets.Max(r => r.ChangesetId);
			Assert.AreEqual(expected, actual);
		}
	}
}
